package com.dabaozhan.modules.wx_app.facade.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.ImageOperation;
import com.dabaozhan.common.utils.RandomUtils;
import com.dabaozhan.common.utils.Utils;
import com.dabaozhan.modules.wx_app.dao.SiteOrderImgMapper;
import com.dabaozhan.modules.wx_app.entity.PurchaseFormEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOrderEntity;
import com.dabaozhan.modules.wx_app.entity.SiteOrderImgEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.SiteOrderFacade;
import com.dabaozhan.modules.wx_app.service.PurchaseFormService;
import com.dabaozhan.modules.wx_app.service.SiteOrderService;

@Service("siteOrderFacade")
public class SiteOrderFacadeImpl implements SiteOrderFacade{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SiteOrderFacade.class);
	
	@Autowired
	private SiteOrderService siteOrderService;

	@Autowired
	private SiteOrderImgMapper siteOrderImgMapper;

	@Autowired
	private PurchaseFormService purchaseFormService;

	@Override
	public SiteOrderEntity createSiteOrder(SiteOrderEntity entity,String pathUrl) {
		//只保留两位小数
		entity.setGrossWeight(entity.getGrossWeight().setScale(2,BigDecimal.ROUND_DOWN));
		entity.setTareWeight(entity.getTareWeight().setScale(2,BigDecimal.ROUND_DOWN));
		entity.setOffWeight(entity.getOffWeight().setScale(2,BigDecimal.ROUND_DOWN));
		entity.setPrice(entity.getPrice().setScale(2,BigDecimal.ROUND_DOWN));
		entity.setNetWeight(entity.getNetWeight().setScale(2,BigDecimal.ROUND_DOWN));
		entity.setMoneyTotal(entity.getMoneyTotal().setScale(2,BigDecimal.ROUND_DOWN));
		//生成订单号
		String orderNumber = RandomUtils.random6();
		String siteOrderiId= Utils.id().toString();
		entity.setId(siteOrderiId);
		entity.setOrderNumber(orderNumber);
		//未支付状态
		entity.setOrderStatus("4");
		//已经审核
		entity.setOrderCheck(2);
		//手工录单 由入参传入
		//entity.setOrderType(3);
		Date currentDate = new Date();
		entity.setCreateTime(currentDate);
		//插入数据
		int result = siteOrderService.saveSiteOrder(entity);
		if(result > 0){
			List<String> picList = entity.getPictureList();
			//图片不为空  插入图片数据
			if(!CollectionUtils.isEmpty(picList)){
				for(int i=0;i<picList.size();i++){
					String picture = picList.get(i);
					if(i<=3 && !StringUtils.isEmpty(picture)){
						//获取文件目录图片 并保存到七牛
						String picUrl = "";
						try{
							picUrl = ImageOperation.encodeImage(picture.substring(picture.lastIndexOf("/") + 1), pathUrl);
						}catch(Exception e){
							LOGGER.error("上传并删除本地图片异常:",e);
						}
						if(StringUtils.isBlank(picUrl)){
							continue;
						}
						SiteOrderImgEntity imgEntity = new SiteOrderImgEntity();
						imgEntity.setId(Utils.id().toString());
						imgEntity.setSiteOrderId(siteOrderiId);
						imgEntity.setPicUrl(picUrl);
						//1:进站 2:出站 3:手工录入
						imgEntity.setPicType(3);
						siteOrderImgMapper.addSiteOrderImg(imgEntity);
					}
				}
			}
			
			PurchaseFormEntity purchaseForm = new PurchaseFormEntity();
			//单价
			purchaseForm.setArrivePrice(entity.getPrice());
			//品类id
			purchaseForm.setCategoryId(entity.getCategoryId());
			//品类父id
			purchaseForm.setParentId(entity.getParentId());
			//供应商名称
			purchaseForm.setName(entity.getName());
			//总重量
			purchaseForm.setTotalWeight(entity.getNetWeight());
			//总价
			purchaseForm.setTotalPrice(entity.getMoneyTotal());
			//打包站id
			purchaseForm.setUserId(entity.getUserId());
			//供应商id
			purchaseForm.setSupplierId(entity.getSupplierId());
			//订单编号
			purchaseForm.setOrderNumber(orderNumber);
			//订单状态
			purchaseForm.setOrderStatus("4");
			//添加采购报表数据
			purchaseFormService.savePurchaseForm(purchaseForm);
			
			SiteOrderEntity  responseEntity = new SiteOrderEntity();
			responseEntity.setOrderNumber(orderNumber);
			responseEntity.setCreateTime(currentDate);
			responseEntity.setId(entity.getId());
			return responseEntity;
		}else{
			//未成功插入数据，抛出业务异常 在controller里面捕获
			throw new RRException(ResponseCodeEnum.ResponseCode_102.getCode(),ResponseCodeEnum.ResponseCode_102.getDescription());
		}
	}

	@Override
	public SiteOrderEntity getSiteOrderByOrderNumber(String orderNumber) {
		SiteOrderEntity entity = siteOrderService.getSiteOrderByOrderNumber(orderNumber);
		if(null == entity){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		List<SiteOrderImgEntity> imgList = siteOrderImgMapper.getSiteOrderImgEntity(entity.getId());
		if(!CollectionUtils.isEmpty(imgList)){
			entity.setPictureImgList(imgList);
		}
		return entity;
	}
		
	//计算净重   净重=毛重-皮重-扣重
	private static BigDecimal getNetWeight(BigDecimal grossWeight,BigDecimal tareWeight,BigDecimal offWeight){
		if( grossWeight.compareTo(BigDecimal.ZERO) < 0 || tareWeight.compareTo(BigDecimal.ZERO) < 0 || offWeight.compareTo(BigDecimal.ZERO) < 0){
			//输入的重量不能小于0
			throw new RRException(ResponseCodeEnum.ResponseCode_104.getCode(),ResponseCodeEnum.ResponseCode_104.getDescription());
		}
		BigDecimal netWeight = grossWeight.subtract(tareWeight).subtract(offWeight);
		if( netWeight.compareTo(BigDecimal.ZERO) < 0){
			//计算的得出的净重不能小于等于0
			throw new RRException(ResponseCodeEnum.ResponseCode_104.getCode(),ResponseCodeEnum.ResponseCode_104.getDescription());
		}
		return netWeight;
	}
	//计算总价
	private static BigDecimal getTotalPrice(BigDecimal price,BigDecimal netWeight){
		BigDecimal result =  price.multiply(netWeight).setScale(2,BigDecimal.ROUND_DOWN);
		return result;
	}
	
}
